# _*_ coding:utf-8 _*_
from flask import Blueprint, render_template
import requests
import pandas as pd
import time
import json

jingwei_page = Blueprint('jingwei_page', __name__)

class LngLat:

    # 读取数据
    def read_data(self):
        file_path = r'location_data.csv'
        file_data = pd.read_csv(file_path, encoding='utf-8')
        duplicate_removal = file_data.drop_duplicates()
        house_names = duplicate_removal['位置']
        house_names = house_names.tolist()
        return house_names

    def get_url(self):
        url_temp = "https://api.map.baidu.com/geocoding/v3/?address={}&output=json&ak=XJjilf81oGQE9yXbdSFm1mvEDh2YZWFE&callback=showLocation"
        house_names = self.read_data()
        return [url_temp.format(i) for i in house_names]

    # 发送请求
    def parse_url(self, url):
        max_retries = 5  # 最大重试次数
        retries = 0
        while retries < max_retries:
            try:
                r = requests.get(url)
                r.raise_for_status()  # 检查请求是否成功
                return r.content.decode('utf-8')
            except requests.exceptions.ConnectionError:
                retries += 1
                time.sleep(2)
            except requests.exceptions.HTTPError as e:
                print(f"HTTPError: {e}")
                break
            except requests.exceptions.RequestException as e:
                print(f"Error: {e}")
                break
        return None  # 如果多次重试失败，返回None

    def run(self):
        li = []
        urls = self.get_url()
        for url in urls:
            data = self.parse_url(url)
            if data is None:
                continue
            try:
                json_data = json.loads(data.split("showLocation&&showLocation(")[-1].split(")")[0])
                lng = json_data['result']['location']['lng']
                lat = json_data['result']['location']['lat']
            except (ValueError, KeyError, json.JSONDecodeError):
                continue
            # 构建字典
            dict_data = {'lng': lng, 'lat': lat, 'count': 1}
            li.append(dict_data)

        with open(r'jingwei_data.txt', 'w', encoding='utf-8') as f:
            f.write(json.dumps(li, ensure_ascii=False, indent=4))

        return li


@jingwei_page.route('/heatmap.html')
def heatmap():
    execute = LngLat()
    points = execute.run()
    return render_template('heatmap.html', points=points)

if __name__ == '__main__':
    execute = LngLat()
    execute.run()
